//
//  WelcomeViewController.swift
//  sinaWeibo
//
//  Created by LSY on 15/12/19.
//  Copyright © 2015年 lsy. All rights reserved.
//

import UIKit

import SnapKit
import SDWebImage
class WelcomeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
//        给欢迎界面添加背景图片
        view = backgroundView
       setUpUI()
        showAnimation()
        
    }

//    添加子控件，并添加约束
    private func setUpUI(){
    
        view.addSubview(iconView)
        view.addSubview(welcomeLable)
        
//        添加约束
        
        iconView.snp_makeConstraints { (make) -> Void in
            
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-200)
//            设置大小
            make.size.equalTo(CGSize(width: 90, height: 90))
        }
//        添加lable的约束
    welcomeLable.snp_makeConstraints { (make) -> Void in
        
        make.centerX.equalTo(iconView.snp_centerX)
        make.top.equalTo(iconView.snp_bottom).offset(20)
        
        }
        
        
//        设置图片
        iconView.sd_setImageWithURL(AccountViewModel().heardUrl, placeholderImage: UIImage(named: "avatar_default_big"))
        
//       将图像变成圆型的
        iconView.layer.cornerRadius = 45
//       裁剪
        iconView.layer.masksToBounds = true
        
    }
    
//    添加动画
    private func  showAnimation(){
    
    
//        首先设置label的透明度
        welcomeLable.alpha = 0
//       修改底部约束
        let offset = -UIScreen.mainScreen().bounds.height + 200
       iconView.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.98, initialSpringVelocity: 9.8, options: [], animations: { () -> Void in
            
//            强制刷新页面，将收集的所有约束更改
            self.view.layoutIfNeeded()
            
            }) { (_) -> Void in
                
//                添加动画
                UIView.animateWithDuration(0.5, animations: { () -> Void in
//                    将透明度调整回来
                    self.welcomeLable.alpha = 1
                    
                    }, completion: { (_) -> Void in
                        
                        print("OK")
                        
//                        当页面加载完成后发出切换页面的通知
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: nil)
                })
        }
    }
    
//    懒加载欢迎界面的视图
    private lazy var backgroundView :UIImageView = UIImageView(image: UIImage(named: "ad_background"))
    
//    懒加载用户头像的View
    private lazy var iconView:UIImageView = UIImageView()
    
//    懒加载lable
    private lazy var welcomeLable:UILabel = UILabel(title: (AccountViewModel().userName ?? "") + "欢迎回来", color: UIColor.lightGrayColor(), fontSize: 16)
    
}
